﻿package com.edward.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.struts2.ServletActionContext;
import org.springframework.security.annotation.Secured;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.userdetails.UserDetails;

import com.edward.JsonDateProcessor;
import com.edward.PagerModel;
import com.edward.model.Cargo;
import com.edward.model.DT_Cargo;
import com.edward.model.DepotList;
import com.edward.model.SL_Cargo;
import com.edward.model.ShoppingList;
import com.edward.service.CargoManager;
import com.edward.service.DT_CargoManager;
import com.edward.service.DepotListManager;
import com.edward.service.SL_CargoManager;
import com.edward.service.ShoppingListManager;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class DepotListAction extends ActionSupport {

	private static final long serialVersionUID = 6447929072069317197L;

	private DepotListManager depotListManager;
	
	private DT_CargoManager dt_CargoManager;
	
	private ShoppingListManager shoppingListManager;
	
	private SL_CargoManager sl_CargoManager;

	private CargoManager cargoManager;
	
	private DepotList depotList;
	
	private DT_Cargo dt_Cargo;
	
	private Cargo cargo;
	
	private int id;
	
	private int slId = 0;
	
	private int limit;
	
	private int start;
	
	private String query;
	
	private String tab;
	
	private String location;
	
	private boolean oversea = false;
	
	private boolean flag = false;

	

	public int getSlId() {
		return slId;
	}


	public void setSlId(int slId) {
		this.slId = slId;
	}


	public int getId() {
		return id;
	}


	public void setId(int id) {
		this.id = id;
	}


	public DepotList getDepotList() {
		return depotList;
	}


	public void setDepotList(DepotList depotList) {
		this.depotList = depotList;
	}


	public DT_Cargo getDt_Cargo() {
		return dt_Cargo;
	}


	public void setDt_Cargo(DT_Cargo dtCargo) {
		dt_Cargo = dtCargo;
	}


	public void setDepotListManager(DepotListManager depotListManager) {
		this.depotListManager = depotListManager;
	}


	public void setDt_CargoManager(DT_CargoManager dtCargoManager) {
		dt_CargoManager = dtCargoManager;
	}
	
	
	
	public void setShoppingListManager(ShoppingListManager shoppingListManager) {
		this.shoppingListManager = shoppingListManager;
	}


	public void setSl_CargoManager(SL_CargoManager slCargoManager) {
		sl_CargoManager = slCargoManager;
	}


	public Cargo getCargo() {
		return cargo;
	}


	public void setCargo(Cargo cargo) {
		this.cargo = cargo;
	}


	public void setCargoManager(CargoManager cargoManager) {
		this.cargoManager = cargoManager;
	}
	
	public int getLimit() {
		return limit;
	}


	public void setLimit(int limit) {
		this.limit = limit;
	}


	public int getStart() {
		return start;
	}


	public void setStart(int start) {
		this.start = start;
	}
	
	public String getQuery() {
		return query;
	}


	public void setQuery(String query) {
		this.query = query;
	}
	

	public boolean isFlag() {
		return flag;
	}


	public void setFlag(boolean flag) {
		this.flag = flag;
	}


	public boolean isOversea() {
		return oversea;
	}


	public void setOversea(boolean oversea) {
		this.oversea = oversea;
	}


	public String getTab() {
		return tab;
	}


	public void setTab(String tab) {
		this.tab = tab;
	}

	public String getLocation() {
		return location;
	}


	public void setLocation(String location) {
		this.location = location;
	}


	//添加depotlist 的表头
	@Secured("ROLE_DEPOT_ADD")
	public String add() throws Exception{
		ActionContext ctx = ActionContext.getContext();        
		  HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
		depotList.setListNum(depotListManager.listNum(depotList.getFlag()));
		UserDetails userDetails = (UserDetails) SecurityContextHolder
				.getContext().getAuthentication().getPrincipal();
		depotList.setAuditor(depotListManager.getUserName(userDetails.getUsername()));
		depotListManager.addDepotList(depotList);
		String w = depotList.getWarehouse();
		if(w.equals("E")||w.equals("F")||w.equals("G")){
			oversea = true;
		}
		int total = depotListManager.listDepotList(depotList.getFlag(),oversea).size();
		response.getWriter().print("{success : true , msg : '添加成功!',depotList_id:"+ depotList.getId()+",total:" + total + "}");
		return null;
	}
	
	@Secured("ROLE_DEPOT_UPDATE")
	public String update() throws Exception{
		ActionContext ctx = ActionContext.getContext();        
		HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
		DepotList d = depotListManager.getDepotList(depotList.getId());
		depotList.setGoods(d.getGoods());
		depotList.setAuditor(d.getAuditor());
		depotListManager.updateDepotList(depotList);
		response.getWriter().print("{success : true , msg : '修改成功!'}");
		return null;
	}
	
	@Secured("ROLE_DEPOT_UPDATE")
	public String delete() throws Exception{
		ActionContext ctx = ActionContext.getContext();        
		HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
		DepotList d = depotListManager.getDepotList(depotList.getId());
		if(d.getGoods().size() != 0){
			response.getWriter().print("{success : false , msg : '删除失败，存在入库货物列表，请先删除入库货物!'}");
		}else{
			depotListManager.deleteDepotList(d.getId());
			response.getWriter().print("{success : true , msg : '删除成功!'}");
		}
		return null;
	}
	
	@Secured("ROLE_DEPOT")
	public String getList() throws Exception {

		ActionContext ctx = ActionContext.getContext();        
		HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
	    JsonConfig cfg = new JsonConfig();
		cfg.registerJsonValueProcessor(java.util.Date.class, new JsonDateProcessor());
		cfg.registerJsonValueProcessor(java.sql.Date.class, new JsonDateProcessor());
		PagerModel pager;
		if(flag){
			pager = depotListManager.pagerList(start, limit ,tab, oversea,depotList);
		}else{
			pager = depotListManager.pagerList(start, limit ,tab, oversea);
		}
		JSONObject jsonObject = JSONObject.fromObject(pager,cfg);
		String jsonStr = jsonObject.toString();
		response.getWriter().print(jsonStr);
		return null;
	}
	

	
	//添加depotlist 的 货物明细
	@Secured("ROLE_DEPOT_ADD")
	public String addDTCargo() throws Exception{
		ActionContext ctx = ActionContext.getContext();        
		HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
		DepotList d = depotListManager.getDepotList(depotList.getId());
		//判断列表中是否一存在该货物
		List <DT_Cargo>l  = d.getGoods();
		for (DT_Cargo dd : l) {
			if(dd.getCargo().getCode().equals(cargo.getCode())){
				response.getWriter().print("{failure:true, msg : '添加失败，货物列表中以存在该货物'}");
				return null;
			}
			
		}
		cargo.setCount(dt_Cargo.getAmount());
		Cargo c = cargoManager.getCargo(cargo.getId());
		//判断搜索得来的 提示cargo 是不是该仓库中的CARGO
		if(c!=null &&c.getLocation()!=null&&!c.getLocation().equals(d.getWarehouse())){
			Cargo v = cargoManager.checkCargo(d.getWarehouse(), cargo.getCode());
			if(v == null){
				cargo.setId(0);
			}else{
				cargo.setId(v.getId());
			    c = v;
			}
			cargo.setOrigin(c.getOrigin());
			cargo.setPrice(dt_Cargo.getPrice());
			cargo.setLocation(d.getWarehouse());
		}
	
		//判断货物是新建的还是以有的
		if(cargo.getId() == 0&&d.getFlag().equals("入库")){
			//判断同一个仓库不能有相同名称或者编号噶货物
			if(cargoManager.check(cargo)){
				response.getWriter().print("{failure:true, msg : '添加失败，该仓库存在编号或者同名称的货物!'}");
				return null;
			}
			cargo.setPrice(dt_Cargo.getPrice());
			cargo.setLocation(d.getWarehouse());
			cargoManager.addCargo(cargo);
			//当入库类型为收货的时候，减去中途仓中对应的货物
			if(d.getType().equals("收货")){
				Cargo z;
				if (cargo.getLocation().equals("A")||cargo.getLocation().equals("B")||cargo.getLocation().equals("C")){
					 z = cargoManager.checkCargo("Y", cargo.getCode());
				}else{
					 z = cargoManager.checkCargo("X", cargo.getCode());
				}
				if(dt_Cargo.getAmount()>z.getCount()){
					response.getWriter().print("{failure:true, msg : '添加失败，入库数量大于中途仓的库存!'}");
					return null;
				}else{
					z.setCount(z.getCount()-dt_Cargo.getAmount());
					cargoManager.updateCargo(z);
				}
			}
		}else{
			if(c.getSign() != null){
				if(c.getSign().equals("sl")){
					cargo.setSign("dt");
				}else{
					cargo.setSign(c.getSign());
				}
			}
			cargo.setOrigin(c.getOrigin());
			cargo.setPrice(dt_Cargo.getPrice());
			cargo.setLocation(d.getWarehouse());
			if(d.getFlag().equals("入库")){
				
				//当入库类型为收货的时候，减去中途仓中对应的货物
				if(d.getType().equals("收货")){
					Cargo z;
					if (cargo.getLocation().equals("A")||cargo.getLocation().equals("B")||cargo.getLocation().equals("C")){
						 z = cargoManager.checkCargo("Y", cargo.getCode());
					}else{
						 z = cargoManager.checkCargo("X", cargo.getCode());
					}
					if(dt_Cargo.getAmount()>z.getCount()){
						response.getWriter().print("{failure:true, msg : '添加失败，入库数量大于中途仓的库存!'}");
						return null;
					}else{
						z.setCount(z.getCount()-dt_Cargo.getAmount());
						cargoManager.updateCargo(z);
					}
				}
				
				
			if(slId!= 0){	
				//入库的时候 更新 采购项中以采购数量，并判断采购单是否完成
				SL_Cargo  sl  = sl_CargoManager.getSL_Cargo(slId);
			//应找到采购单S 而非采购项sl
//				if(!sl.getState().equals("正在采购")){
//					response.getWriter().print("{failure:true, msg : '添加失败，此采购单非正在采购状态，不能生成入库!'}");
//					return null;
//				}
				sl.setCount(sl.getCount()+dt_Cargo.getAmount());
				if(sl.getCount()>=sl.getAmount()){
					sl.setState("以完成");
				}
				sl_CargoManager.updateSL_Cargo(sl);
				ShoppingList s = sl_CargoManager.getSL(slId);
				List<SL_Cargo> sList = s.getGoods();
				boolean x = true;
				for(SL_Cargo sl_cargo : sList){
					if(sl_cargo.getState().equals("未完成")){
						x = false;
						break;
					}
				}
				if(x){
					s.setState("已完结");
					shoppingListManager.updateShoppingList(s);
				}
			}
				
				
				
				cargo.setCount(c.getCount()+cargo.getCount());
			}else{
				if(c.getCount()-cargo.getCount()<0){
					response.getWriter().print("{failure:true, msg : '添加失败，此货物在该仓库中库存不足!'}");
					return null;
				}
				cargo.setCount(c.getCount()-cargo.getCount());
			}
			cargoManager.updateCargo(cargo);
		}
		dt_Cargo.setCargo(cargo);
		dt_Cargo.setSum(dt_Cargo.getPrice() * dt_Cargo.getAmount());
		dt_CargoManager.addDT_Cargo(dt_Cargo);
		d.getGoods().add(dt_Cargo);
		depotListManager.updateDepotList(d);
		response.getWriter().print("{success : true , msg : '添加成功!'}");
		return null;
	}
	
	@Secured("ROLE_DEPOT_UPDATE")
	public String updateDTCargo() throws Exception {

		ActionContext ctx = ActionContext.getContext();        
		HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
		DT_Cargo dt = dt_CargoManager.getDT_Cargo(dt_Cargo.getId());
		DepotList d = depotListManager.getDepotList(depotList.getId());
//	这里应该考虑判断有没有两个	//判断列表中是否一存在该货物
//		List <DT_Cargo>l  = d.getGoods();
//		for (DT_Cargo dd : l) {
//			if(dd.getCargo().getCode().equals(cargo.getCode())){
//				response.getWriter().print("{failure:true, msg : '修改失败，货物列表中以存在该货物'}");
//				return null;
//			}
//			
//		}
		cargo.setLocation(d.getWarehouse());
		//由于变更的cargo没有Id ,先从数据库中获取其ID 再一同更新
		Cargo c =dt.getCargo();
		cargo.setOrigin(c.getOrigin());
		cargo.setSign(c.getSign());
		if(d.getFlag().equals("入库")){
			
			//当入库类型为收货的时候，减去中途仓中对应的货物
			if(d.getType().equals("收货")){
				Cargo z;
				if (cargo.getLocation().equals("A")||cargo.getLocation().equals("B")||cargo.getLocation().equals("C")){
					 z = cargoManager.checkCargo("Y", cargo.getCode());
				}else{
					 z = cargoManager.checkCargo("X", cargo.getCode());
				}
				if(dt_Cargo.getAmount()-dt.getAmount()>z.getCount()){
					response.getWriter().print("{failure:true, msg : '添加失败，入库数量大于中途仓的库存!'}");
					return null;
				}else{
					z.setCount(z.getCount()-dt_Cargo.getAmount()+dt.getAmount());
					cargoManager.updateCargo(z);
				}
			}
			
			
			//入库的时候 更新 采购项中以采购数量，并判断采购单是否完成
		 ShoppingList shopping =  shoppingListManager.getShoppingList(d.getOrderNum());
		 if(shopping != null){	
			List<SL_Cargo> tmpList =  shopping.getGoods();
			for(SL_Cargo tmp : tmpList){
				if(tmp.getCargo().getId() == cargo.getId()){
					slId = tmp.getId();
					break;
				}
			}
			SL_Cargo  sl  = sl_CargoManager.getSL_Cargo(slId);
			sl.setCount(sl.getCount()+dt_Cargo.getAmount()-dt.getAmount());
			if(sl.getCount()>=sl.getAmount()){
				sl.setState("以完成");
			}else{
				sl.setState("未完成");
			}
			sl_CargoManager.updateSL_Cargo(sl);
			ShoppingList s = sl_CargoManager.getSL(slId);
			List<SL_Cargo> sList = s.getGoods();
			boolean x = true;
			for(SL_Cargo sl_cargo : sList){
				if(sl_cargo.getState().equals("未完成")){
					x = false;
					break;
				}
			}
			if(x){
				s.setState("已完结");
			}else{
				s.setState("正在采购");
			}
			shoppingListManager.updateShoppingList(s);
		 }
			
			cargo.setCount(c.getCount() + dt_Cargo.getAmount() - dt.getAmount());
		}else{
			int i = c.getCount() - dt_Cargo.getAmount() + dt.getAmount();
			if(i<0){
				response.getWriter().print("{failure:true, msg : '添加失败，此货物在该仓库中库存不足!'}");
				return null;
			}
			cargo.setCount(i);
		}
		cargo.setId(c.getId());
		cargo.setPrice(dt_Cargo.getPrice());
		dt_Cargo.setSum(dt_Cargo.getPrice() * dt_Cargo.getAmount());
		dt_Cargo.setCargo(cargo);
		//判断同一个仓库不能有相同名称或者编号噶货物
		if(cargoManager.updateCheck(cargo)){
			response.getWriter().print("{failure:true, msg : '修改失败，该仓库存在编号相同或者名称相同的货物!'}");
			return null;
		}
		cargoManager.updateCargo(cargo);
		dt_CargoManager.updateDT_Cargo(dt_Cargo);
		response.getWriter().print("{success : true , msg : '修改成功!'}");
		return null;
	}
	
	@Secured("ROLE_DEPOT_UPDATE")
	public String deleteDTCargo() throws Exception {

		ActionContext ctx = ActionContext.getContext();        
		HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
		DT_Cargo dt = dt_CargoManager.getDT_Cargo(dt_Cargo.getId());
		DepotList d = depotListManager.getDepotList(depotList.getId());
		Cargo c =dt.getCargo();
		//用作途中库的回加
		int amount = dt.getAmount();
		boolean flag = dt_CargoManager.check(c.getId());
		dt_CargoManager.deleteDT_Cargo(dt_Cargo.getId());
		if(flag){
			if(d.getType().equals("收货")){
				Cargo z;
				if (c.getLocation().equals("A")||c.getLocation().equals("B")||c.getLocation().equals("C")){
					 z = cargoManager.checkCargo("Y", c.getCode());
				}else{
					 z = cargoManager.checkCargo("X", c.getCode());
				}
				
					z.setCount(z.getCount()+amount);
					cargoManager.updateCargo(z);
				
			}
			cargoManager.deleteCargo(c.getId());
		}else{
			if(d.getFlag().equals("入库")){
				
				//当入库类型为收货的时候，减去中途仓中对应的货物
				if(d.getType().equals("收货")){
					Cargo z;
					if (c.getLocation().equals("A")||c.getLocation().equals("B")||c.getLocation().equals("C")){
						 z = cargoManager.checkCargo("Y", c.getCode());
					}else{
						 z = cargoManager.checkCargo("X", c.getCode());
					}
					
						z.setCount(z.getCount()+amount);
						cargoManager.updateCargo(z);
					
				}
				
				//入库的时候 更新 采购项中以采购数量，并判断采购单是否完成
				ShoppingList shopping =  shoppingListManager.getShoppingList(d.getOrderNum());
			  if(shopping != null){	
				List<SL_Cargo> tmpList =  shopping.getGoods();
				for(SL_Cargo tmp : tmpList){
					if(tmp.getCargo().getId() == c.getId()){
						slId = tmp.getId();
						break;
					}
				}
				SL_Cargo  sl  = sl_CargoManager.getSL_Cargo(slId);
				sl.setCount(sl.getCount()-dt.getAmount());
				if(sl.getCount()>=sl.getAmount()){
					sl.setState("以完成");
				}else{
					sl.setState("未完成");
				}
				sl_CargoManager.updateSL_Cargo(sl);
				ShoppingList s = sl_CargoManager.getSL(slId);
				List<SL_Cargo> sList = s.getGoods();
				boolean x = true;
				for(SL_Cargo sl_cargo : sList){
					if(sl_cargo.getState().equals("未完成")){
						x = false;
						break;
					}
				}
				if(x){
					s.setState("已完结");
				}else{
					s.setState("正在采购");
				}
				shoppingListManager.updateShoppingList(s);
			  }	
				
				c.setCount(c.getCount() - dt.getAmount() );
			}else{
				c.setCount(c.getCount() + dt.getAmount() );
			}
			
			cargoManager.updateCargo(c);
		}
		
		response.getWriter().print("{success : true , msg : '删除成功!'}");
		return null;
	}
	
	
	//获取grid 显示 的 分页信息
	@Secured("ROLE_DEPOT")
	public String getDTCargo() throws Exception {

		ActionContext ctx = ActionContext.getContext();        
		  HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
		
	  JsonConfig cfg = new JsonConfig();
		cfg.registerJsonValueProcessor(java.util.Date.class, new JsonDateProcessor());
		cfg.registerJsonValueProcessor(java.sql.Date.class, new JsonDateProcessor());
		PagerModel pager;
		
		
			pager = dt_CargoManager.pagerDTCargo(start, limit,depotList.getId());
			 
		JSONObject jsonObject = JSONObject.fromObject(pager,cfg);
		
		String jsonStr = jsonObject.toString();
		response.getWriter().print(jsonStr);
		 
	           
		return null;
	}
	
	//获取编码下拉框自动提示信息
	public String getCargosByCode() throws Exception{
		
		ActionContext ctx = ActionContext.getContext();        
		  HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
		List<Cargo> list = cargoManager.getCodes(query,location);
		Map<String,String> map = new HashMap<String,String>();
		  JSONObject jsonObject=null;
		  String json="";
		for (Cargo cargo : list) {
			 map.put("code",cargo.getCode());
			 jsonObject = JSONObject.fromObject( map );
			 map.clear();
			 json += jsonObject.toString() + ",";
		}
		
		json  = "{\"codes\":[ "  + json.substring(0, json.length()-1) + "]}";
		response.getWriter().print(json);
		return null;
	}
	
	
	public String getCargosByname() throws Exception {
			
			ActionContext ctx = ActionContext.getContext();        
			HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
			response.setContentType("text/html;charset=UTF-8");
			List<Cargo> list = cargoManager.getNames(query,location);
			Map<String,String> map = new HashMap<String,String>();
			  JSONObject jsonObject=null;
			  String json="";
			for (Cargo cargo : list) {
				 map.put("name",cargo.getName());
				 jsonObject = JSONObject.fromObject( map );
				 map.clear();
				 json += jsonObject.toString() + ",";
			}
			json  = "{\"names\":[ "  + json.substring(0, json.length()-1) + "]}";
			response.getWriter().print(json);
			return null;
	}
	
	
	//通过code获取下拉框中仓库以有cargo的信息
	public String getCode() throws Exception {

		ActionContext ctx = ActionContext.getContext();        
		  HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
		Cargo  c = cargoManager.getCode(query);
		JSONObject jsonObject = JSONObject.fromObject(c);
		String jsonStr = jsonObject.toString();
		response.getWriter().print(jsonStr);
		 
	           
		return null;
	}

	//获取姓名下拉框自动提示信息
	public String getName() throws Exception {
		
		ActionContext ctx = ActionContext.getContext();        
		HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
		response.setContentType("text/html;charset=UTF-8");
		Cargo  c = cargoManager.getName(query);
		if(c ==null){
			response.getWriter().print("{'code':'flag'}");
			return null;
		}
		JSONObject jsonObject = JSONObject.fromObject(c);
		String jsonStr = jsonObject.toString();
		response.getWriter().print(jsonStr);
		
		
		return null;
	}
	
	@Secured("ROLE_DEPOT")
	 public String getListJudge() throws Exception {
			ActionContext ctx = ActionContext.getContext();        
			HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);    
			response.setContentType("text/html;charset=UTF-8");
				response.getWriter().print("{success : true , msg : '成功!',deny:false}");
		 return null;
	 }
	
	
	
}
